package com.eystar.pdc.model;

import java.util.List;

import com.eystar.ext.kit.tree.BaseTree;
import com.eystar.ext.plugin.tablebind.ModelExt;
import com.eystar.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;

import cn.hutool.core.util.StrUtil;

/**
 * 资源 Model
 * 
 * @author zhangjian
 * 
 */
@TableBind(tableName = "t_pdc_resource")
public class Resource extends ModelExt<Resource> {

	private static final long serialVersionUID = 1244431359124317083L;
	public final static Resource dao = new Resource();

	public void refresh(boolean forceRefresh){
		ResourceTree.dao.listResource(forceRefresh);
		ResourceTree.dao.listResourceTree(forceRefresh);
		ResourceTree.dao.listResourceTreeJson(forceRefresh);
		ResourceTree.dao.listResourceMap(forceRefresh);
	}
	
	public List<Resource> findAll(){
		SqlPara sqlPara = getSqlPara("pdc.resource.findAll");
		return find(sqlPara);
	}
	
	/**
	 * 添加成功后，更新资源路径
	 * @param resource
	 */
	public void addResourcePath(Resource resource){
		String id = resource.getStr("id");
		String pid = resource.getStr("res_pid");
		if (StrUtil.equals(pid, "0")) { // 如果修改后的父节点ID为0
			resource.set("res_path", "/0/"+id+"/");
		}else {
			Resource presource = Resource.dao.findById(pid);
			resource.set("res_path", presource.getStr("res_path")+id+"/");
		}
		resource.update();
	}
	
	/**
	 * 修改成功后，修改资源路径
	 * @param resource
	 */
	public void updateResourcePath(Resource resource){
		String id = resource.getStr("id"); // 资源本身ID
		resource = Resource.dao.findById(id);
		
		String res_path = resource.getStr("res_path"); // 资源修改前本身路径
		String pid = resource.getStr("res_pid"); // 修改之后的父级节点
		String res_path2 = "";
		if (StrUtil.equals(pid, "0")) { // 如果修改后的父节点ID为0
			res_path2 = "/0/"+id+"/";
		}else {
			Resource presource = Resource.dao.findById(pid);
			res_path2 = presource.getStr("res_path")+id+"/";
		}
		if (!StrUtil.equals(res_path, res_path2)) {
			String sql = getSql("pdc.resource.updateResourcePath");
			Db.update(sql,res_path,res_path2);
		}
	}
	
	/**
	 * 按地址删除资源
	 * @param id
	 */
	public void deleteResourceById(String id){
		// 1、删除资源同时删除该节点的关联节点
		String sql1 = getSql("pdc.resource.deleteResourceById_1");
		Db.update(sql1,id);
		// 2、删除不存在的角色资源分配关系表
		String sql2 = getSql("pdc.resource.deleteResourceById_2");
		Db.update(sql2);
	}
	
	public BaseTree toBaseTree(){
		BaseTree tree = new BaseTree();
		tree.setId(this.getStr("id"));
		tree.setParentId(this.getStr("res_pid"));
		tree.setNodeName(this.getStr("res_name"));
		tree.setAttrs(this._getAttrs());
		return tree;
	}
}